package edu.gu.hajo.gcl.parser;

import edu.gu.hajo.gcl.interp.IInterpreter;
import edu.gu.hajo.gcl.script.Script;

/**
 * Paring words NOT starting with { or ". Ending with whitespace or ; Assumes
 * leading char is present!
 * 
 * @author hajo
 * @inv non, stateless
 */
public final class StringParser {

	private final IInterpreter interp;
	private final BracesParser bracesParser;
	private final VarParser varParser;
	private final CmdSubstParser cmdSubstParser;

	public StringParser(IInterpreter interp, BracesParser bracesParser,
			VarParser varParser, CmdSubstParser cmdSubstParser) {
		this.interp = interp;
		this.bracesParser = bracesParser;
		this.varParser = varParser;
		this.cmdSubstParser = cmdSubstParser;

	}

	public String parse(Script script) {

		String part = null;
		StringBuffer buffer = new StringBuffer();

		Parser.parseSpace(script);

		char ch;
		while ((ch = script.next()) != 0) {
			switch (ch) {
			case '[':
				script.putBack();
				String cmd = cmdSubstParser.parse(script);
				interp.eval(new Script(cmd));
				part = interp.getResult();
				buffer.append(part);
				break;
			case '$':
				script.putBack();
				String name = varParser.parse(script);
				part = interp.getVar(name);
				buffer.append(part);
				break;
			case '{':
				script.putBack();
				part = bracesParser.parse(script);
				buffer.append(part);
				break;
			case ' ':
			case '\t':
			case '\r':
			case '\n':
			case ';':
				script.putBack();
				return buffer.toString();
			default:
				buffer.append(ch);
			}
		}
		return buffer.toString();
	}
}
